package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 好友服务接口实现类
 */
@Service
public class FriendApiImpl implements FriendApi{


    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addContacts(Long friendId, Long userId) {
        //1.根据当前登录用户id 和  好友id 查询tanhua_users记录是否存在
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        Friend friend = mongoTemplate.findOne(query, Friend.class);
        if(friend == null){
            friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setId(ObjectId.get());
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //2.根据好友id 和   当前登录用户id 查询tanhua_users记录是否存在
        Query query2 = new Query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        Friend friend2 = mongoTemplate.findOne(query2, Friend.class);
        if(friend2 == null){
            friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setId(ObjectId.get());
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    /**
     * 查询联系人列表
     * @param page
     * @param pagesize
     * @param keyword
     * @return
     */
    @Override
    public PageResult<Friend> queryContacts(Integer page, Integer pagesize, String keyword,Long userId) {
        page=page<1?1:page;
        //1.总记录数
        PageRequest pageRequest = PageRequest.of(page-1,pagesize);
        Query query = new Query(Criteria.where("userId").is(userId));
        if(StringUtils.isNotEmpty(keyword)){
            query.addCriteria(Criteria.where("friendId").is(keyword));
        }
        query.with(pageRequest);
        long counts = mongoTemplate.count(query, Friend.class);
        //2.根据条件分页查询小视频列表
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //3.封装返回PageResult
        long pages = counts/pagesize + counts%pagesize > 0 ? 1:0;
        return new PageResult<Friend>(counts,(long)pagesize,pages,(long)page,friendList);
    }
}
